<!-- 素材管理 -->
<template>
  <el-dialog title="素材管理" :close-on-click-modal="false" :visible.sync="visible" fullscreen center append-to-body>
    <el-button class="miui-dialog-close-btn" @click="closeHandle">关闭页面</el-button>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" size="medium" label-width="120px">
      <el-form-item label="微信公众号" prop="wxAccount">
        <el-select v-model="dataForm.wxAccount" placeholder="请选择">
          <el-option v-for="item in wxAccountOptions" :key="item.account" :label="item.name" :value="item.account"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="素材类型" prop="messageType">
        <el-select v-model="dataForm.messageType" placeholder="请选择">
            <el-option label="文本信息" :value="1"></el-option>
            <el-option label="图文信息" :value="2"></el-option>
          </el-select>
      </el-form-item>
      <el-form-item label="素材主题" prop="messageTheme">
        <el-input v-model="dataForm.messageTheme" placeholder="请输入20个字以内"></el-input>
      </el-form-item>


      <div style="margin-top: 20px;">
        <el-form-item label="标题" prop="messageTitle">
          <el-input v-model="dataForm.messageTitle" type="textarea" placeholder="请输入1024个字以内"></el-input>
        </el-form-item>
        <div v-if="dataForm.messageType == 2">
          <el-form-item label="消息描述" prop="messageDescription">
            <el-input v-model="dataForm.messageDescription" type="textarea" placeholder="请输入30个字以内"></el-input>
          </el-form-item>
          <el-form-item label="封面图片URL">
            <el-input v-model="dataForm.imageUrl" placeholder="请输入30个字以内" disabled>
              <!-- action="/mp/wxImage/uploadFile" -->
              <el-upload slot="append"
                v-if="dataForm.messageType == 2"
                class="upload-demo"
                :show-file-list="false"
                action="/mp/wxImage/uploadMediaToWechat"
                :headers="headers"
                :data="das"
                :before-upload="beforeUpload"
                :on-success="handleSuccess"
                :disabled="!dataForm.wxAccount"
                >
                <el-button size="small" type="primary">点击上传</el-button>
              </el-upload>
            </el-input>

          </el-form-item>
          <el-form-item label="连接类型">
            <el-select v-model="dataForm.linkType" placeholder="请选择">
              <el-option label="直接跳转到一个网站" :value="1"></el-option>
              <el-option label="内部文章" :value="2"></el-option>
            </el-select>

            <el-button v-if="dataForm.linkType == 2" @click="articleCheckHandle">选择</el-button>
          </el-form-item>
          <el-form-item label="连接URL" v-if="dataForm.linkType == 1">
            <el-input v-model="dataForm.linkUrl"></el-input>
          </el-form-item>
          <el-form-item label="参数内容" v-if="dataForm.linkType == 2">
            <el-input v-model="dataForm.articleName"></el-input>
          </el-form-item>
        </div>
      </div>

      <div v-if="dataForm.messageType == 2" style="margin: 0 auto;margin-top: 20px;width: 350px;height: 220px;border: solid 1px #c3c3c3;padding: 10px;background-color: #e9f2f7;">
        <div style="width: 330px;height: 200px;background-color: #fff;">
          <div style="width: 100%;height: 150px;border-bottom: solid 1px #c3c3c3;overflow: hidden;">
            <img :src="dataForm.imageUrl" alt="" style="width: 330px;height: 150px;">
          </div>
          <div style="width: 100%;line-height: 30px;font-size: 18px;font-weight: 600;margin-left: 10px;">
            {{dataForm.messageTitle}}
          </div>
          <div style="width: 100%;line-height: 20px;margin-left: 10px;">
            {{dataForm.messageDescription}}
          </div>
        </div>
      </div>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button size="medium" type="primary" @click="dataFormSubmit" :loading="ischeck" v-prevent-re-click>保 存</el-button>
    </span>

    <search-article v-if="articleVisible" ref="articleDialog" @refreshData="getArticleData"></search-article>
  </el-dialog>
</template>

<script>
  import store from '@/store'
  import { mapGetters } from 'vuex'
  import { fetchAccountList } from '@/api/mp/wxaccount'
  import {getWxMaterialObj, addWxMaterialObj, putWxMaterialObj, WxMaterialDel} from '@/api/mp/wxmaterial'

  import SearchArticle from '@/views/mp/_components/SearchArticle'

  var myDate = new Date();

  export default {
    data(){
      return {
        visible: false,
        ischeck: false,
        headers: {
          'Authorization': 'Bearer ' + store.getters.access_token,
        },
        das: {},
        dataForm: {
          materType: '',

        },
        originMediaIds: [],
        wxAccountOptions: {},
        dataRule: {
          messageTheme: [{required: true, message: '素材主题不能为空', trigger: 'blur' }],
          messageTitle: [{required: true, message: '标题不能为空', trigger: 'blur' }],
          messageDescription: [{required: true, message: '消息描述不能为空', trigger: 'blur' }],
          imageUrl: [{required: true, message: '封面图片不能为空', trigger: 'blur' }]
        },
        articleVisible: false
      }
    },
    components: {
      SearchArticle
    },
    methods: {
      init(id){
        this.visible = true
        this.originMediaIds = []
        for(let key in this.dataForm){
          if(key != 'imageMediaId'){
            this.$set(this.dataForm,key,'')
          }
        }
        this.$set(this.dataForm,'id',id || 0)
        this.$set(this.dataForm,'mediaId','')
        this.$set(this.dataForm,'messageType',1)
        this.$set(this.dataForm,'linkType',1)
        this.$set(this.dataForm,'imageMediaId','')

        this.getAccountList()

        this.$nextTick(() => {
          if(this.dataForm.id){
            getWxMaterialObj(this.dataForm.id).then(response => {
              this.dataForm = response.data.data
              this.oldPicId = this.dataForm.imageMediaId
              this.originMediaIds.push(this.oldPicId)
            })
          }
        })
      },
      handleSuccess(res,file){
        if(res.data){
          this.$set(this.dataForm,'imageUrl',res.data.url)
          // this.$set(this.dataForm,'mediaId',res.data.mediaId)
          this.$set(this.dataForm,'imageMediaId',res.data.mediaId)

          this.originMediaIds.push(res.data.mediaId)
        }


      },
      // 打开选择文章弹窗
      articleCheckHandle(){
        this.articleVisible = true
        this.$nextTick(() => {
          this.$refs.articleDialog.init()
        })
      },
      // 获取文章信息
      getArticleData(data){
        this.$set(this.dataForm,'articleId',data.id)
        this.$set(this.dataForm,'articleName',data.title)
      },
      // 上传图片之前
      beforeUpload(file){
        this.$set(this.das,'wxAccount',this.dataForm.wxAccount)
        this.$set(this.das,'type','thumb')
      },
      // 保存
      dataFormSubmit(){
        this.ischeck = true
          this.$refs['dataForm'].validate((valid) => {
            if (valid) {
              let delIndex = this.originMediaIds.length - 1
              this.originMediaIds.splice(delIndex,1)
              this.dataForm.originMediaIds = this.originMediaIds
              if (this.dataForm.id) {
                putWxMaterialObj(this.dataForm).then(data => {
                  this.$message.success('修改成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                  setTimeout(() => {
                    this.ischeck = false
                  },500)
                }).catch(() => {
                  this.ischeck = false
                })
              } else {
                addWxMaterialObj(this.dataForm).then(data => {
                  this.$message.success('添加成功')
                  this.visible = false
                  this.$emit('refreshDataList')
                  setTimeout(() => {
                    this.ischeck = false
                  },500)
                }).catch(() => {
                  this.ischeck = false
                })
              }
            }else{
              this.ischeck = false
            }
          })
      },
      // 获取公众号信息
      getAccountList() {
        fetchAccountList().then(result => {
          this.wxAccountOptions = result.data.data
        })
      },
      // 关闭弹窗
      closeHandle(){
        if(this.oldPicId){
          let delIndex = this.originMediaIds.findIndex(item => item === this.oldPicId)
          this.originMediaIds.splice(delIndex, 1)
        }
        if(this.dataForm.wxAccount && this.originMediaIds.length > 0){
          WxMaterialDel({wxAccount: this.dataForm.wxAccount,originMediaIds: this.originMediaIds})
        }
        this.visible = false
      },


      imgToBase64(url,cb){
            var canvas = document.createElement('canvas'),
              ctx = canvas.getContext('2d'),
            img = new Image;

            img.crossOrigin = 'Anonymous';
            img.onload = function () {
              canvas.height = img.height;
              canvas.width = img.width;
              ctx.drawImage(img, 0, 0);
              var dataURL = canvas.toDataURL('image/png');
              cb && cb(dataURL);
              canvas = null;
            };
            img.src = url;
          },
          //base64转file对象
          base64toFile(base, filename){
            var arr = base.split(',');
            var mime = arr[0].match(/:(.*?);/)[1];
            var suffix = mime.split("/")[1];
            var bstr = atob(arr[1]);
            var n = bstr.length;
            var u8arr = new Uint8Array(n);
            while (n--) {
              u8arr[n] = bstr.charCodeAt(n);
            }
            //转换成file对象
            return new File([u8arr], `${filename}.${suffix}`, { type: mime });
          },
    }
  }
</script>

<style lang="scss" scoped>
  table {
    width: 100%;
  }

  tr td {
    border: solid 1px #e7e7e7;
  }
  /deep/ .el-upload-list {
    display: none!important;
  }
</style>
